<template>
  <nav class="navbar">
    <div class="container">
      <div class="logo">
        <router-link to="/">E-Shop</router-link>
      </div>
      <div class="nav-links">
        <router-link to="/products" class="nav-link">商品列表</router-link>
        <router-link to="/cart" class="nav-link" v-if="authStore.isAuthenticated">
          购物车 <el-badge :value="cartCount" class="item" />
        </router-link>
        <router-link to="/profile" class="nav-link" v-if="authStore.isAuthenticated">个人中心</router-link>
        <template v-else>
          <router-link to="/login" class="nav-link">登录</router-link>
          <router-link to="/register" class="nav-link">注册</router-link>
        </template>
      </div>
    </div>
  </nav>
</template>

<script setup lang="ts">
import { ref, onMounted, watch } from 'vue';
import { useAuthStore } from '../stores/auth';
import { cartService } from '../api/cartService';

const authStore = useAuthStore();
const cartCount = ref(0);

const fetchCartCount = async () => {
  if (authStore.isAuthenticated) {
    try {
      const cartResponse = await cartService.getCart();
      cartCount.value = cartResponse.data.summary.totalItems;
    } catch (error) {
      console.error('获取购物车数量失败:', error);
      cartCount.value = 0;
    }
  } else {
    cartCount.value = 0;
  }
};

// 监听认证状态变化，更新购物车数量
watch(() => authStore.isAuthenticated, () => {
  fetchCartCount();
});

onMounted(() => {
  fetchCartCount();
});
</script>

<style scoped>
.navbar {
  background-color: #fff;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  position: sticky;
  top: 0;
  z-index: 100;
}

.navbar .container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 60px;
}

.logo a {
  font-size: 24px;
  font-weight: bold;
  color: #409eff;
  text-decoration: none;
}

.nav-links {
  display: flex;
  gap: 20px;
}

.nav-link {
  color: #333;
  text-decoration: none;
  padding: 8px 16px;
  border-radius: 4px;
  transition: all 0.3s;
}

.nav-link:hover {
  background-color: #f5f5f5;
  color: #409eff;
}
</style>